package com.qianfeng.entity;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;

/**
 * 购物车
 * 
 * @author ChenZeTao 2018年9月18日 下午5:20:48
 */
public class ShopCar {

	// 存放商品集合
	private List<GoodInfo> list = new ArrayList<>();

	// 提供一辆购物车
	public static ShopCar getShopCar(HttpSession session) {
		ShopCar shopCar = (ShopCar) session.getAttribute("SHOP_CAR");
		if (shopCar == null) {
			shopCar = new ShopCar();
			session.setAttribute("SHOP_CAR", shopCar);
		}
		return shopCar;
	}

	// 添加商品
	public void add(GoodInfo gi) {
		boolean flag = true;
		for (GoodInfo goodInfo : getList()) {
			if (goodInfo.getId() == gi.getId()) {
				goodInfo.setCount(goodInfo.getCount() + gi.getCount());
				flag = false;
				return;
			}
		}

		if (flag) {
			// 没有该 商品，就添加到购物车中
			getList().add(gi);
		}
	}

	// 移除商品
	public void remove(int id) {
		for (GoodInfo goodInfo : getList()) {
			if (goodInfo.getId() == id) {
				// 移除
				getList().remove(goodInfo);
				return;
			}
		}
	}

	// 修改商品数量
	public GoodInfo update(int id, int count) {
		for (GoodInfo goodInfo : getList()) {
			if (goodInfo.getId() == id) {
				goodInfo.setCount(count);
				return goodInfo;
			}
		}
		return null;
	}
	// 购物车商品总价格

	public double getTotalPrice() {
		BigDecimal totalPrice = new BigDecimal(String.valueOf(0));
		for (GoodInfo goodInfo : getList()) {
			totalPrice = totalPrice.add(new BigDecimal(String.valueOf(goodInfo.getDanPrice())));
		}
		return totalPrice.doubleValue();
	}

	// 购物车商品的个数
	public int getTypeCount() {
		return getList().size();
	}

	public List<GoodInfo> getList() {
		return list;
	}

	public void setList(List<GoodInfo> list) {
		this.list = list;
	}
}
